/**
 * The Community Project
 * Copyright Team1 Productions
 * 
 * Joshua Amick
 * Stephen Cunningham
 * Thema Davis
 * Tomika Dawson
 * Lucie DeCristofaro
 * 
 * All Rights Reserved.
 */

package com.actions;

import java.sql.Timestamp;
import java.util.regex.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.business.PrivateManager;
import com.business.PublicManager;
import com.forms.EditProfileForm;
import com.forms.ProfileDateForm;
import com.constants.UserPermissions;
import com.domain.Profile;
import com.domain.User;


public class SaveProfileAction extends CommunityBaseAction{
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		super.execute(mapping, form, request, response);

		// Cast the actionForm, if there is one.
		ActionForward forward;
		EditProfileForm f = (EditProfileForm) form;

		PublicManager publicMgr = this.biz.getPublicMgr();
		PrivateManager privateMgr = this.biz.getPrivateMgr();
		User user = (User) request.getSession().getAttribute("AUTH_USER");		
		
		//Checking user
		if (user==null)
		{
			forward = mapping.findForward("failure");
			request.setAttribute("ERRORS", "User could not be found");			
		}
		else
		{
			//FIELD CHECKING START
			
			String		strRet	= "";
			Timestamp	gradTS	= null;
			Timestamp	empTS	= null;
			
			// saving the dates for the EditProfile.jsp to display
			// replaced by AUTH_USER_PROFILE_FORM
			/*
			ProfileDateForm dateForm = new ProfileDateForm();
			dateForm.setEmpStartDay(f.getEmpStartDay());
			dateForm.setEmpStartMonth(f.getEmpStartMonth());
			dateForm.setEmpStartYear(f.getEmpStartYear());
			dateForm.setGradDay(f.getGradDay());
			dateForm.setGradMonth(f.getGradMonth());
			dateForm.setGradYear(f.getGradYear());
			
			this.populateAuthUserProfileForm(f);
			
			request.getSession().setAttribute("AUTH_USER_PROFILE_DATE_FORM", dateForm);
			*/
			
			if (f.getSubscribedToEmails()=="false")
				user.setSubscribedToEmails(false);
			else
				user.setSubscribedToEmails(true);

			boolean publiclyViewable = false;
			if (f.getPublicViewable()=="false")
				publiclyViewable = false;
			else
				publiclyViewable = true;			
			
			if (!f.isDateEmpty(f.getGradDay(), f.getGradMonth(), f.getGradYear()))
			{				
				gradTS = f.getDateTimestamp(f.getGradYear(), f.getGradMonth(), f.getGradDay());
				if (gradTS==null)
					strRet += "Invalid Date in Graduation Date</br>";
			}
			if (!f.isDateEmpty(f.getEmpStartDay(), f.getEmpStartMonth(), f.getEmpStartYear()))
			{
				empTS = f.getDateTimestamp(f.getEmpStartYear(), f.getEmpStartMonth(), f.getEmpStartDay());
				if (empTS==null)
					strRet += "Invalid Date in Start Employment Date</br>";
			}
			if (f.getZip()!=null&&f.getZip().length()>0)
			{
				if (!Pattern.matches("[0-9]{5}", f.getZip()))
					strRet += "Invalid Zipcode</br>";
			}
			if (f.getPhone()!=null&&f.getPhone().length()>0)
			{
				if (Pattern.matches("[1-9][0-9]{9}", f.getPhone()))
				{
					String formattedPhone = f.getPhone().substring(0,3)+"-"+f.getPhone().substring(3, 6)+"-"+f.getPhone().substring(6, 10);
					f.setPhone(formattedPhone);
				}
				else if (!Pattern.matches("^[1-9]{1}[0-9]{2}-[0-9]{3}-[0-9]{4}$", f.getPhone()))
					strRet += "Invalid phone number</br>";
			}
			if (f.getSecondaryEmail()!=null&&f.getSecondaryEmail().length()>0)
			{
				/*
				if (!Pattern.matches("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$",
						f.getSecondaryEmail()));
					strRet += "Invalid email address\r\n";
					*/
			}
			if (f.getState().equals("State"))
			{
				// no state was selected
				f.setState("");
			}

			this.populateAuthUserProfileForm(f,request);
			
			if(f.getMajor().equals("Major"))f.setMajor(null);
			
//			FIELD CHECKING END
			
			if (strRet.length()>0)
			{
				// errors were found in the form
				forward = mapping.findForward("failure");
				request.setAttribute("ERRORS", strRet);
				//request.setAttribute("FORM", f);				
			}
			else
			{
				//Saving user
				// no errors found
				forward = mapping.findForward("success");
				request.setAttribute("INFO", "Profile was successfully saved");	
				user = privateMgr.saveProfileForUser(user, f.getFirstName(), 
						f.getLastName(), f.getAddress1(), f.getAddress2(),
						f.getCity(), f.getState(), f.getZip(), f.getSecondaryEmail(), 
						f.getPhone(), f.getEmployer(), f.getPositionDescription(), 
						empTS, f.getEducation(), f.getMajor(), gradTS, 
						f.getProfessionalOrganizations(), f.getStudentOrganizations(), publiclyViewable);			
				
				request.getSession().setAttribute("AUTH_USER", user);
			}
		}

		return forward;
	}	

	//Populate method for profile form
	private void populateAuthUserProfileForm(EditProfileForm form, HttpServletRequest request)
	{
		EditProfileForm f = new EditProfileForm();
		f.setAddress1(form.getAddress1());
		f.setAddress2(form.getAddress2());
		f.setCity(form.getCity());
		f.setEducation(form.getEducation());
		f.setEmployer(form.getEmployer());
		f.setEmpStartDay(form.getEmpStartDay());
		f.setEmpStartMonth(form.getEmpStartMonth());
		f.setEmpStartYear(form.getEmpStartYear());
		f.setFirstName(form.getFirstName());
		f.setGradDay(form.getGradDay());
		f.setGradMonth(form.getGradMonth());
		f.setGradYear(form.getGradYear());
		f.setFirstName(form.getFirstName());
		f.setIsAdminUser(form.getIsAdminUser());
		f.setLastName(form.getLastName());
		f.setMajor(form.getMajor());
		f.setPhone(form.getPhone());
		f.setPositionDescription(form.getPositionDescription());
		f.setProfessionalOrganizations(form.getProfessionalOrganizations());
		f.setPublicViewable(form.getPublicViewable());
		f.setSecondaryEmail(form.getSecondaryEmail());
		f.setState(form.getState());
		f.setStudentOrganizations(form.getStudentOrganizations());
		f.setSubscribedToEmails(form.getSubscribedToEmails());
		f.setZip(form.getZip());
		
		request.getSession().setAttribute("AUTH_USER_PROFILE_FORM", f);
	}
}
